package com.ccteam.fluidmusic.ui.setting

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.utils.preference.SettingWorker
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class SettingActivity : AppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {

    @Inject lateinit var onceRequest: OneTimeWorkRequest

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting)

    }

    override fun onPreferenceStartFragment(
        caller: PreferenceFragmentCompat?,
        pref: Preference?
    ): Boolean {
        when(pref?.fragment){
            "com.ccteam.fluidmusic.ui.setting.AboutFragment" ->{
                findNavController(R.id.setting_nav_host_container).navigate(FluidMusicSettingsFragmentDirections.actionFluidMusicSettingsFragmentToAboutFragment())
            }
            "com.ccteam.fluidmusic.ui.setting.EditPasswordFragment" ->{
                findNavController(R.id.setting_nav_host_container).navigate(FluidMusicSettingsFragmentDirections.actionFluidMusicSettingsFragmentToEditPasswordFragment())
            }
            "com.ccteam.fluidmusic.ui.setting.EditOldPhoneFragment" ->{
                findNavController(R.id.setting_nav_host_container).navigate(FluidMusicSettingsFragmentDirections.actionFluidMusicSettingsFragmentToEditPhoneFragment())
            }
        }
        return true
    }

    override fun onStop() {
        super.onStop()

        // 在退出设置界面时，进行WorkManager内容的执行用于同步设置数据
        WorkManager.getInstance(this).enqueueUniqueWork(
            SettingWorker.SETTING_WORKER_ONCE_TAG,ExistingWorkPolicy.REPLACE,
            onceRequest
        )
    }
}